<?php

Loader::using(array(
    'underscore::libs::MEF::CompositionInitializer',
    'underscore::libs::MEF::Container::Default',
));

/**
 * A custom MEF composition initializer with static factories suport.
 * In order to use the static factory of an object, it should be annotated
 * with <code>@export-metadata singleinstance</code> and 
 * <code>@export-metadata static-factory:factoryMethodName</code>
 */
class UnderscoreCompositionInitializer extends MEF_CompositionInitializer {

    /**
     * 
     * 
     * @param string $exportClassName
     * @param array $metaData
     * @return mixed 
     */
    protected function createInstance($exportClassName, $metaData) {

        //Expected singleton
        if (in_array('singleinstance', $metaData)) {
            $metaDataCollection = new MetadataCollection($metaData);
            
            //Has a static factory?
            if ($metaDataCollection->has("static-factory")) {
                $meta = $metaDataCollection->find("static-factory");
                $factory = explode(":", $meta);
                $factoryMethod = $factory[1];

                $instance = $exportClassName::$factoryMethod();

                if (!array_key_exists($exportClassName, $this->_instances)) {
                    $this->satisfyImports($instance);
                }

                $this->_instances[$exportClassName] = $instance;
            }
        }
        
        return parent::createInstance($exportClassName, $metaData);
    }

}

?>
